/*
 *
 * LegendShop 多用户商城系统
 *
 *  版权所有,并保留所有权利。
 *
 */
package com.legendshop.oa.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.legendshop.oa.dto.AdminUserTaskEstimateDto;
import com.legendshop.oa.dto.ProjectReport;
import com.legendshop.util.Arith;
import com.legendshop.util.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.legendshop.dao.support.PageSupport;
import com.legendshop.framework.controller.BaseController;
import com.legendshop.oa.constants.PathResolver;
import com.legendshop.oa.model.AdminUser;
import com.legendshop.oa.pages.AdminTilesPage;
import com.legendshop.oa.util.PageSupportHelper;
import com.legendshop.permission.service.AdminUserService;
import com.legendshop.util.AppUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 我的团队
 */
@Controller
@RequestMapping("/admin/myteam")
public class MyTeamController extends BaseController {

    /**
     * The log.
     */
    private final static Logger log = LoggerFactory.getLogger(MyTeamController.class);

    @Autowired
    private AdminUserService adminUserService;

    /**
     * 项目下的列表查询
     */
    @RequestMapping("/query")
    public String queryProjectTask(HttpServletRequest request, HttpServletResponse response, String curPageNO, AdminUser adminUser, Date startDate, Date endDate) {

        if (AppUtils.isNotBlank(adminUser.getName())) {
            AdminUser user = adminUserService.getAdminUserByUserName(adminUser.getName());
            if (user != null) {
                request.setAttribute("userRealName", user.getRealName());
            }
        }
        Date date = new Date();
        if (startDate == null) {
            //今年第一天
            startDate = getFirstDayOfThisMonth();
        }

        if (endDate == null) {
            endDate = date;
        }

        PageSupport<AdminUser> ps = adminUserService.getAdminUserByDept(curPageNO, adminUser, startDate, endDate);

        //查询每个周报
        PageSupportHelper.savePage(request, ps);
        request.setAttribute("bean", adminUser);
        request.setAttribute("startDate", startDate);
        request.setAttribute("endDate", endDate);

        return PathResolver.getPath(request, response, AdminTilesPage.MYTEAM_PAGE);
    }


    /**
     * 每个人在各个项目的时间消耗
     */
    @RequestMapping("/userReport/{userName}")
    public String userReport(HttpServletRequest request, HttpServletResponse response, @PathVariable String userName, Date startDate, Date endDate) {
        AdminUser user = null;
        if (AppUtils.isNotBlank(userName)) {
            user = adminUserService.getAdminUserByUserName(userName);
            if (user != null) {
                request.setAttribute("userRealName", user.getRealName());
            }
        }
        Date date = new Date();
        if (startDate == null) {
            //今年第一天
            startDate = getFirstDayOfThisMonth();
        }

        if (endDate == null) {
            endDate = date;
        }

        List<AdminUserTaskEstimateDto> list = adminUserService.getAdminUserTaskEstimate(userName, startDate, endDate);

        request.setAttribute("list", list);
        request.setAttribute("user", user);
        request.setAttribute("startDate", startDate);
        request.setAttribute("endDate", endDate);

        List<String> names = list.stream().map(i -> i.getProjectName()).collect(Collectors.toList());
        List<Double> consumed = list.stream().map(i -> new BigDecimal(i.getConsumed()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()).collect(Collectors.toList());

        request.setAttribute("names", JSONUtil.getJson(names));
        request.setAttribute("consumed", JSONUtil.getJson(consumed));


        Double totalConsumedHours = 0d;
        if(AppUtils.isNotBlank(list)) {
            for (AdminUserTaskEstimateDto dto : list) {
                if(AppUtils.isNotBlank(dto.getConsumed())) {
                    totalConsumedHours = Arith.add(totalConsumedHours, dto.getConsumed());
                }
            }
        }
        request.setAttribute("totalConsumedHours",  new BigDecimal(totalConsumedHours).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        return PathResolver.getPath(request, response, AdminTilesPage.USER_REPORT_LIST_PAGE);
    }


    /**
     * 获取当年的第一天
     *
     * @return
     */
    private Date getCurrYearFirst() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    private Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }


    /**
     * 获取当前月份第一天的日期 * @return 格式化后的日期
     */
	private Date getFirstDayOfThisMonth() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return cal.getTime();
    }

}
